package com.soft.bams.client;

import com.soft.bams.service.Bank;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ATMClient extends JFrame {
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardPanel = new JPanel(cardLayout);
    private Bank bank = Bank.getInstance();

    private MainPanel mainPanel;
    private RegisterPanel registerPanel;
    private LoginPanel loginPanel;
    private BusinessPanel businessPanel;

    private Socket socket;
    private PrintWriter out;
    private ObjectInputStream in;

    public Object sendCommand(String command) {
        try {
            out.println(command);
            return in.readObject();
        } catch (IOException | ClassNotFoundException e) {
            return "通信错误: " + e.getMessage();
        }
    }

    public ATMClient() {
        initComponents();
        setupFrame();

        try {
            socket = new Socket("localhost", 8888);
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new ObjectInputStream(socket.getInputStream());
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "无法连接到服务器", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }

        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                Object response = sendCommand("removeIdFromIdIpMap#" + getBusinessPanel().getCurrentAccount().getId());
                JOptionPane.showMessageDialog(null,response);
            }
        });

    }

    private void initComponents() {
        mainPanel = new MainPanel(this);
        registerPanel = new RegisterPanel(this);
        loginPanel = new LoginPanel(this);
        businessPanel = new BusinessPanel(this);

        cardPanel.add(mainPanel, "Main");
        cardPanel.add(registerPanel, "Register");
        cardPanel.add(loginPanel, "Login");
        cardPanel.add(businessPanel, "Business");

        this.add(cardPanel);
    }

    private void setupFrame() {
        this.setTitle("ATM系统");
        this.setSize(600, 450);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
    }

    public void showPanel(String panelName) {
        cardLayout.show(cardPanel, panelName);
    }

    public Bank getBank() {
        return bank;
    }

    public BusinessPanel getBusinessPanel() {
        return businessPanel;
    }

    public static void main(String[] args) {
        new ATMClient().setVisible(true);
      }
}